package com.permission.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.permission.constant.Constants;
import com.permission.dto.response.user.PicCaptchaResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @desc: 图形验证码工具类
 * @author: xhs
 * @date: 2022/10/10 14:50
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class VerifyUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成图形验证码
     * @return PicCaptchaResponse
     */
    public PicCaptchaResponse getPicCaptcha() {
        // 定义图形验证码的长、宽、字符个数、干扰线条数
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 38, 4, 80);
        // 获取验证码的值
        String validCode = captcha.getCode();
        // 获取验证码的base64
        String validCodeBase64 = captcha.getImageBase64Data();
        // 生成请求号
        String validCodeReqNo = IdWorker.getIdStr();
        // 将请求号作为key，验证码的值作为value放到redis，用于校验，2分钟有效
        redisTemplate.opsForValue().set(Constants.CAPTCHA + validCodeReqNo, validCode, 2 * 60, TimeUnit.SECONDS);
        PicCaptchaResponse captchaResponse = new PicCaptchaResponse();
        captchaResponse.setValidCodeBase64(validCodeBase64);
        captchaResponse.setValidCodeReqNo(validCodeReqNo);
        return captchaResponse;
    }
}
